<template>
  <ElDialog v-model="dialogVisible" :title="dialogType === 'add' ? '添加用户' : '编辑用户'" width="30%" align-center>
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="用户名" prop="username">
        <ElInput v-model="formData.username" placeholder="请输入用户名" />
      </ElFormItem>
      <ElFormItem label="姓名" prop="name">
        <ElInput v-model="formData.name" placeholder="请输入姓名" />
      </ElFormItem>
      <ElFormItem label="密码" prop="password">
        <ElInput v-model="formData.password" placeholder="请输入密码" />
      </ElFormItem>
      <ElFormItem label="邮箱" prop="email">
        <ElInput v-model="formData.email" placeholder="请输入邮箱" />
      </ElFormItem>
      <ElFormItem label="部门" prop="department">
        <ElSelect v-model="formData.department" :filterable="true" :clearable="true">
          <ElOption v-for="d in deptOptions" :key="d.value" :value="d.value" :label="d.label" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="关联员工" prop="person_id">
        <ElSelect v-model="formData.person_id" :filterable="true" :clearable="true">
          <ElOption v-for="s in salerOptions" :key="s.value" :value="s.value" :label="s.label" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色" prop="roles">
        <ElSelect v-model="formData.roles" multiple :filterable="true" :clearable="true">
          <ElOption v-for="r in roleOptions" :key="r.value" :value="r.value" :label="r.label" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { createUser, updateUser } from '@/api/system/user'
import { HttpError } from '@/utils/http/error'


interface Props {
  visible: boolean
  type: string
  userData?: any
  departments?: Array<{ dept_code: string; dept_name: string }>
  roles?: Array<{ id: number; name: string }>
  salers?: Array<{ id: string; name: string }>
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 选项列表（基于 props）
const deptOptions = computed(() => (props.departments || []).map((d) => ({ label: d.dept_name, value: d.dept_code })))
const salerOptions = computed(() => (props.salers || []).map((s) => ({ label: s.name, value: s.id })))
const roleOptions = computed(() => (props.roles || []).map((r) => ({ label: r.name, value: r.id })))

// 对话框显示控制
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const dialogType = computed(() => props.type)

// 表单实例
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive({
  username: '',
  name: '',
  password: '',
  email: '',
  department: '',
  phone: '',
  person_id: '',
  roles: [] as number[]
})

// 表单验证规则
const rules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'blur' }],
  email: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  person_id: [{ required: true, message: '请选择员工', trigger: 'blur' }],
  roles: [{ required: true, message: '请选择角色', trigger: 'blur' }]
}

// 初始化表单数据
const initFormData = () => {
  const isEdit = props.type === 'edit' && props.userData
  const row = props.userData

  Object.assign(formData, {
    username: isEdit ? row.username || '' : '',
    name: isEdit ? row.name || '' : '',
    department: isEdit ? row.department || '' : '',
    email: isEdit ? row.email || '' : '',
    person_id: isEdit ? String(row.person_id) : '',
    roles: isEdit ? Array.isArray(row.roles) ? row.roles.map(Number) : [] : []
  })
}

// 统一监听对话框状态变化
watch(
  () => [props.visible, props.type, props.userData, props.roles],
  ([visible]) => {
    if (visible) {
      initFormData()
      nextTick(() => {
        formRef.value?.clearValidate()
      })
    }
  },
  { immediate: true }
)

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    // 构造请求体，与后端 UserCreate/UserUpdate 对齐
    const basePayload = {
      username: formData.username,
      name: formData.name || undefined,
      email: formData.email || undefined,
      password: formData.password,
      department: formData.department || undefined,
      phone: formData.phone || undefined,
      person_id: formData.person_id ? Number(formData.person_id) : undefined,
      roles: (formData.roles || []).map((r) => Number(r))
    }

    try {
      if (dialogType.value === 'add') {
        // 后端创建用户需要 password，使用默认初始密码
        await createUser({
          ...basePayload
        })
        // 成功提示由请求封装根据后端 msg 显示
      } else {
        const id = props.userData?.id
        if (!id) {
          ElMessage.error('缺少用户ID，无法更新')
          return
        }
        await updateUser(id, basePayload)
        // 成功提示由请求封装根据后端 msg 显示
      }

      dialogVisible.value = false
      emit('submit')
    } catch (err) {
      // 请求封装已根据后端msg弹出错误（如“用户名已存在”），此处避免重复提示
      console.error('提交失败', err)
      if (!(err instanceof HttpError)) {
        ElMessage.error('提交失败，请稍后重试')
      }
    }
  })
}
</script>
